package com.example.demo.mqserver.datacenter;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张
 * Date: 2024-08-13
 * Time: 10:07
 */

import com.example.demo.common.MqException;
import com.example.demo.mqserver.core.Binding;
import com.example.demo.mqserver.core.Exchange;
import com.example.demo.mqserver.core.MSGQueue;
import com.example.demo.mqserver.core.Message;
import org.apache.ibatis.annotations.Mapper;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * 使用这个类管理硬盘数据
 * 1.数据库: 交换机,绑定,队列
 * 2,数据文件:消息
 */
@Mapper
// 数据存储调用类
public class DiskDataCenter {
    //管理数据库中的数据
    private DataBaseManager dataBaseManager = new DataBaseManager();
    //管理数据文件中的数据
    private MessageFileManager messageFileManager = new MessageFileManager();

    //初始化
    public void init() {
        dataBaseManager.init();
        messageFileManager.init();
    }

    //封装交换机操作
    public void insertExchange(Exchange exchange) {
        dataBaseManager.insertExchange(exchange);
    }

    public void deleteExchange(String exchangeName){
        dataBaseManager.deleteExchange(exchangeName);
    }

    public List<Exchange> selectAllExchanges() {
        return dataBaseManager.selectAllExchanges();
    }

    //封装队列  ---  不仅仅是在数据库,数据文件也需要进行创建和删除
    public void insertQueue (MSGQueue queue) throws IOException {
        dataBaseManager.insertQueue(queue);
        messageFileManager.createQueueFiles(queue.getName());
    }

    public void deleteQueue(String queueName) throws IOException {
        dataBaseManager.deleteQueue(queueName);
        messageFileManager.destroyQueueFiles(queueName);
    }

    public List<MSGQueue> selectAllQueues() {
        return dataBaseManager.selectAllQueues();
    }

    //封装绑定
    public void insertBinding (Binding binding) {
        dataBaseManager.insertBinding(binding);
    }

    public void deleteBinding (Binding binding) {
        dataBaseManager.deleteBinding(binding);
    }

    public List<Binding> selectAllBindings () {
        return  dataBaseManager.selectAllBindings();
    }

    //封装消息
    public void sendMessage(MSGQueue queue, Message message) throws IOException, MqException {
        messageFileManager.sendMessage(queue,message);
    }

    public void deleteMessage(MSGQueue queue,Message message) throws IOException, ClassNotFoundException, MqException {
        messageFileManager.deleteMessage(queue,message);
        //考虑是否要进行GC操作
        if (messageFileManager.checkGC(queue.getName())) {
            messageFileManager.gc(queue);
        }
    }

    public LinkedList<Message> loadAllMessageFromQueues(String queueName) throws IOException, MqException, ClassNotFoundException {
        return messageFileManager.loadAllMessageFromQueue(queueName);
    }


}
